package com.qj.platform.pay.filter;

import com.qj.base.commons.utils.RSA;
import com.qj.base.filter.AbstractFilter;
import com.qj.platform.pay.commons.execption.SdsCodeDefinition;
import com.qj.platform.pay.commons.execption.SdsException;
import com.qj.platform.pay.core.holder.OperatorContextHolder;
import com.qj.platform.pay.core.holder.UserContextHolder;
import com.qj.platform.pay.core.domain.Operator;
import com.qj.platform.pay.core.domain.User;
import com.qj.platform.pay.core.service.OperatorService;
import com.qj.platform.pay.core.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by hezhijie on 2016/11/24.
 */
@Component
public class TokenFilter extends AbstractFilter {
    @Value("${tokenFilter.excludes:^/$}")
    private List<Pattern> excludePatternList;
    @Value("${tokenFilter.orderNo:-101}")
    private int orderNo;
    @Autowired
    private UserService userService;
    @Autowired
    private OperatorService operatorService;

    @Override
    public boolean doFilter(HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader("TOKEN");
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter("TOKEN");
        }
        if (StringUtils.isEmpty(token)) {
            throw new SdsException(SdsCodeDefinition.USER_VALID_ERROR);
        }
        try {
            String[] tokenMessage = RSA.getInstance().decrypt(token.replace(" ","+")).split("#");
            if("USER".equals(tokenMessage[0])) {
                User user = userService.getUserByMachineCode(tokenMessage[2]);
                user.setMachineCode(tokenMessage[2]);
                UserContextHolder.setUser(user);
            }else if("OPERATOR".equals(tokenMessage[0])){
                Operator operator = operatorService.getUserByUserName(tokenMessage[2]);
                if(operator==null){
                    throw new SdsException(SdsCodeDefinition.USER_VALID_ERROR);
                }
                OperatorContextHolder.set(operator);
            }
        } catch (Exception e) {
            throw new SdsException(SdsCodeDefinition.USER_VALID_ERROR);
        }
        return true;
    }

    @Override
    public List<Pattern> getExcludePatternList() {
        return excludePatternList;
    }

    @Override
    public int getOrderNo() {
        return orderNo;
    }
//        if(super.getOrderNo()==0){
//            try {
//                super.setOrderNo(Integer.valueOf(orderNo));
//            }catch (Exception e){
//                super.setOrderNo(-100);
//            }
//        }
//        return super.getOrderNo();
//    }
}
